package com.ruoyi.common.utils.file;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.ruoyi.common.config.OssConfig;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import io.minio.MinioClient;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.rmi.RemoteException;
import java.util.Date;
import java.util.UUID;

/**
 * @Description: OSS上传文件工具类
 * @Version: 1.0
 */
public class OssUtil {

    public static String uploadFile( MultipartFile file,String bucketName,String fileName) throws IOException{
        // 填写Object完整路径，例如exampledir/exampleobject.txt。Object完整路径中不能包含Bucket名称。
        // String objectName = "exampledir/exampleobject.txt";

        // 创建OSSClient实例。
        OSS ossClient = SpringUtils.getBean(OSS.class);

        try {
            InputStream inputStream = file.getInputStream();
            // 获取文件后缀设置content-type
            ObjectMetadata objectMetadata = new ObjectMetadata();
            String extension = FileUploadUtils.getExtension(file);

            switch (extension.toLowerCase()) {
                case "jpg":
                case "jpeg":
                case "png":
                case "gif":
                case "bmp":
                    objectMetadata.setContentType(extension);
            }

            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, fileName, inputStream, objectMetadata);
            // 设置该属性可以返回response
            putObjectRequest.setProcess("true");
            // 创建上传请求
            PutObjectResult result = ossClient.putObject(putObjectRequest);
            if(result.getResponse().getStatusCode() == 200){
                // 图片添加水印
                String uri = result.getResponse().getUri() + "?x-oss-process=style/Watermark";
                System.err.println("上传成功!"+uri);
                return uri;
            }


        } catch (OSSException oe){
            System.out.println("捕获到OSSException，这意味着您的请求已发送到OSS，但由于某种原因被拒绝并出现错误响应。");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce){
            System.out.println("捕获了一个ClientException，这意味着客户端遇到了试图与OSS沟通时出现严重的内部问题，例如无法访问网络");
            System.out.println("Error Message:" + ce.getMessage());

        } catch (Exception e){
            e.printStackTrace();
        }
        throw new RuntimeException("上传错误");
    }
}
